<template>
  <div id="cesium">
    <div id="cesiumContainer"></div>
    <div id="loadingbar" class="spinner">
      <div class="spinner-container container1">
        <div class="circle1"></div>
        <div class="circle2"></div>
        <div class="circle3"></div>
        <div class="circle4"></div>
      </div>
      <div class="spinner-container container2">
        <div class="circle1"></div>
        <div class="circle2"></div>
        <div class="circle3"></div>
        <div class="circle4"></div>
      </div>
      <div class="spinner-container container3">
        <div class="circle1"></div>
        <div class="circle2"></div>
        <div class="circle3"></div>
        <div class="circle4"></div>
      </div>
    </div>
    <div id="tool-menu" class="tool-menu">
      <a
        data-toggle="dropdown"
        id="layerMangerBtn"
        title="图层管理"
        class="tool-menu-btn tool-menu-btn-inverse"
      >
        <span class="smicon-layerlist tool-menu-btn-icon"></span>
        <div class="dropDown-container treeview-dropDown-container" id="treeContainer">
          <div id="layerTree"></div>
        </div>
      </a>
      <a class="tool-menu-btn tool-menu-btn-inverse" style="padding: 10px 0px"
        ><span style="border-left: 1px solid #dddddd"></span
      ></a>
      <div id="tool-menu-btn-group" class="tool-menu-btn-group">
        <a
          data-toggle="dropdown"
          id="colorBtn"
          title="选中颜色"
          class="tool-menu-btn tool-menu-btn-inverse"
        >
          <span class="fui-list-small-thumbnails tool-menu-btn-icon"></span>
          <div class="dropDown-container">
            <div
              style="
                min-width: 100px;
                border-radius: 4px;
                text-align: left;
                padding: 10px;
              "
            >
              <label style="font-size: 8px">选中颜色： </label
              ><input
                class="colorPicker"
                size="8"
                data-bind="value: material,valueUpdate: 'input'"
                id="colorPicker"
              />
            </div>
            <div style="text-align: left; padding: 10px">
              <label>过滤透明度：</label
              ><input
                type="number"
                min="0"
                max="1"
                step="0.1"
                value="0"
                id="select-filter-alpha"
              />
            </div>
          </div>
        </a>
      </div>
    </div>
    <div id="bubble" class="bubble" style="bottom: 0; left: 82%; display: none">
      <div id="tools" style="text-align: right">
        <span
          style="
            color: rgb(255, 255, 255);
            padding: 5px;
            position: absolute;
            left: 10px;
            top: 4px;
          "
          >对象属性</span
        >
        <span
          class="fui-export"
          id="bubblePosition"
          style="color: rgb(255, 255, 255); padding: 5px"
          title="停靠"
        ></span>
        <span
          class="fui-cross"
          title="关闭"
          id="close"
          style="color: rgb(255, 255, 255); padding: 5px"
        ></span>
      </div>
      <div style="overflow-y: scroll; height: 300px" id="tableContainer">
        <table id="tab"></table>
      </div>
    </div>
    <div>
      <div id="position">
        <div @click="tableTree = !tableTree">数据模型数据查询</div>
        <div id="clearbox" @click="box()">模型切割</div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "cesiumview",
  data() {
    return {
      options: {},
      URL: "http://192.168.1.3:8090/iserver/services/3D-ceshi/rest/realspace",
      list: [],
      tableTree: false,
      boxTrue: true,
      boxNew: false,
    };
  },
  computed: {},
  props: {},
  mounted() {
    window.startupCalled = true;
    this.initialize();
    // this.CameraViewGo();
    // this.onload();
  },
  watch: {
    tableTree(newVal, oldVal) {
      if (newVal) {
        $("#bubble").show();
      } else {
        $("#bubble").hide();
      }
    },
    // boxTrue(newVal, oldVal) {
    //   console.log("boxTrue", newVal);
    //   console.log("boxNew", this.boxNew);

    //   if (this.boxNew) {
    //     this.box();
    //   }
    // },
  },
  methods: {
    initialize() {
      // 初始化viewer部件
      let that = this;
      var viewer = new Cesium.Viewer("cesiumContainer");
      viewer.imageryLayers.addImageryProvider(
        new Cesium.BingMapsImageryProvider({
          url: "https://dev.virtualearth.net",
          mapStyle: Cesium.BingMapsStyle.AERIAL,
          key: URL_CONFIG.BING_MAP_KEY,
        })
      );
      window.$disaviewer = viewer;
      // var viewer = new Cesium.Viewer("cesiumContainer", {
      //   shouldAnimate: true,
      // });
      var scene = viewer.scene;
      scene.sun.show = true;
      // 01设置环境光的强度-新处理CBD场景
      scene.lightSource.ambientLightColor = new Cesium.Color(0.5, 0.5, 0.5, 1);
      // scene.lightSource.ambientLightColor = new Cesium.Color(0.65, 0.65, 0.65, 1);
      // scene.globe.show = false;
      var imageryLayers = viewer.imageryLayers;
      var baseLayer = imageryLayers.get(0);
      scene.camera.frustum.near = 0.01;

      that.CesiumInit(scene);
      that.getTreeData(scene);
    },
    CesiumInit(scene) {
      let that = this;
      var widget = window.$disaviewer.cesiumWidget;
      var list;
      $("#toolbar").show();
      $("#loadingbar").remove();
      var viewModel = {
        material: "#ffffff",
      };
      $("#colorPicker").spectrum({
        color: "rgba(23,92,239,0.5)",
        showPalette: true,
        showAlpha: true,
        localStorageKey: "spectrum.demo",
        palette: palette,
      });
      Cesium.knockout.track(viewModel);
      var toolbar = document.getElementById("colorBtn");
      Cesium.knockout.applyBindings(viewModel, toolbar);
      try {
        // ("http://192.168.1.3:8090/iserver/services/3D-data/rest/realspace");

        var promise = scene.open(
          "http://192.168.1.251:8090/iserver/services/3D-WorkSpace-2/rest/realspace"
        );
        Cesium.when(
          promise,
          function (layers) {
            //设置相机位置、方向，定位至模型
            scene.camera.setView({
              // destination: new Cesium.Cartesian3(
              //   -2180753.065987198,
              //   4379023.266141494,
              //   4092583.575045952
              // ),
              // orientation: {
              //   heading: 1.5392222751147955,
              //   pitch: 0.010279641987852584,
              //   roll: 1.240962888005015e-11,
              // },
            });

            // var layer = scene.layers.find("buffer");

            let layer = scene.layers.find("BatchModelCache");
            window.$disalayer = layer;
            window.$disalayers = layers;
            //读取子图层信息，通过数组的方式返回子图层的名称以及子图层所包含的对象的IDs
            // console.log(URL_CONFIG.SCENE_BIMBUILDING);
            console.log(scene.layers);

            layer.setQueryParameter({
              url:
                "http://192.168.1.251:8090/iserver/services/data-WorkSpace-2/rest/data",
              // dataSetName: "test5", //对应数据集名称，数据服务
              dataSourceName: "dgdlxmx", //对应数据源名称，数据服务
              isMerge: true,
            });
            datainfo(layer);
            // 初始化选中颜色
            var color = new Cesium.Color.fromCssColorString("rgba(23,92,239,0.5)");
            layer.selectedColor = color;

            // 用户自定义选中颜色
            Cesium.knockout
              .getObservable(viewModel, "material")
              .subscribe(function (newValue) {
                var color = Cesium.Color.fromCssColorString(newValue);
                layer.selectedColor = color;
              });
            //通过服务地址得到子图层信息
            //uncheck子节点递归函数
            function changeNodeToUnchecked(node) {
              if (!node.hasOwnProperty("nodes")) {
                $tree.treeview("uncheckNode", [node.nodeId, { slient: true }]);
                return;
              }
              if (node.hasOwnProperty("nodes") && node.nodes.length > 0) {
                for (var i = 0; i < node.nodes.length; i++) {
                  changeNodeToUnchecked(node.nodes[i]);
                }
              }
              $tree.treeview("uncheckNode", [node.nodeId, { slient: true }]);
            }
            //check子节点的递归函数
            function changeNodeToChecked(node) {
              if (!node.hasOwnProperty("nodes")) {
                if (!node.state.checked) {
                  $tree.treeview("checkNode", [node.nodeId, { slient: true }]);
                }
                return;
              }
              if (node.hasOwnProperty("nodes") && node.nodes.length > 0) {
                for (var i = 0; i < node.nodes.length; i++) {
                  changeNodeToChecked(node.nodes[i]);
                }
              }
              if (!node.state.checked) {
                $tree.treeview("checkNode", [node.nodeId, { slient: true }]);
              }
            }
            //本级节点全部勾选后，勾选上级父节点
            function checkSiblingNode(node) {
              //检查兄弟节点信息
              var sibArr = $tree.treeview("getSiblings", node);
              var allCheck = true;
              if (sibArr.length > 0) {
                for (var i = 0; i < sibArr.length; i++) {
                  if (!sibArr[i].state.checked) {
                    allCheck = false;
                    break;
                  }
                }
              }
              //兄弟节点都已选中后勾选父节点
              if (
                allCheck &&
                node.hasOwnProperty("parentId") &&
                !$tree.treeview("getNode", node.parentId).state.checked
              ) {
                $tree.treeview("checkNode", [node.parentId, { slient: true }]);
              }
            }
            //初始化树形菜单
            var $tree = $("#layerTree").treeview({
              data: [{ text: "模型数据", selectable: false }],
              showIcon: false,
              showCheckbox: true,
              backColor: "transparent",
              color: "#fff",
              //通过NodeChecked状态设置子图层的显示与隐藏的切换
              onNodeChecked: function (evt, node) {
                var ids = [];
                for (var i = 0; i < list.length; i++) {
                  if (list[i].datasetName == node.text) {
                    ids = that.range(list[i].startID, list[i].endID);
                    break;
                  }
                }
                if (ids.length > 0) {
                  layer.visible = true;
                  layer.setOnlyObjsVisible(ids, true);
                } else if (node.text == "影像图层" || node.text == "BingMap") {
                  baseLayer.show = true;
                } else {
                  layer.visible = true;
                }
                checkSiblingNode(node);
                changeNodeToChecked(node);
              },
              onNodeUnchecked: function (evt, node) {
                var ids = [];
                for (var i = 0; i < list.length; i++) {
                  if (list[i].datasetName == node.text) {
                    ids = that.range(list[i].startID, list[i].endID);
                    break;
                  }
                }
                if (ids.length > 0) {
                  // layer.removeAllObjsColor();
                  layer.setOnlyObjsVisible(ids, false);
                } else if (node.text == "影像图层" || node.text == "BingMap") {
                  baseLayer.show = false;
                } else {
                  layer.visible = false;
                }
                if (!node.state.checked) {
                  changeNodeToUnchecked(node);
                }
              },
              //节点被选中时，设该子图层颜色为半透明
              onNodeSelected: function (evt, node) {
                var ids = [];
                for (var i = 0; i < list.length; i++) {
                  if (list[i].datasetName == node.text) {
                    ids = that.range(list[i].startID, list[i].endID);
                  }
                }
                if (ids.length > 0) {
                  layer.releaseSelection();
                  layer.setSelection(ids);
                } else {
                  layer.removeAllObjsColor();
                }
              },
              onNodeUnselected: function (evt, node) {
                for (var i = 0; i < list.length; i++) {
                  if (list[i].datasetName == node.text) {
                    layer.releaseSelection();
                  }
                }
              },
            });
            var rootNode = $tree.treeview("getNode", 0);
            //加载图层
            var S3MNode = $tree.treeview("addNode", [
              rootNode,
              {
                text: "S3M图层",
                showDel: true,
                fontSize: "10pt",
                state: { checked: true },
                selectable: false,
              },
            ]);
            var childNode = $tree.treeview("addNode", [
              S3MNode,
              {
                text: layer._name,
                showDel: true,
                fontSize: "10pt",
                state: { checked: true },
                selectable: false,
              },
            ]);
            //加载子图层
            function datainfo(layer) {
              layer.datasetInfo().then(function (result) {
                that.list = result;
                list = result;
                console.log(list);
                if (list.length > 0) {
                  for (var i = 0; i < list.length; i++) {
                    $tree.treeview("addNode", [
                      childNode,
                      {
                        text: list[i].datasetName,
                        showDel: true,
                        fontSize: "10pt",
                        state: { checked: true },
                      },
                    ]);
                  }
                }
              });
            }
            // 过滤指定透明度一下的要素，选择其后的要素
            layer.selectionFiltrateByTransparency = 0;
            $("#select-filter-alpha").on("input propertychange", function () {
              layer.selectionFiltrateByTransparency = Number(
                $("#select-filter-alpha").val()
              );
            });
          },
          function (e) {
            if (widget._showRenderLoopErrors) {
              var title = "加载SCP失败，请检查网络连接状态或者url地址是否正确？";
              widget.showErrorPanel(title, undefined, e);
            }
          }
        );
      } catch (e) {
        if (widget._showRenderLoopErrors) {
          var title = "渲染时发生错误，已停止渲染。";
          widget.showErrorPanel(title, undefined, e);
        }
      }
    },
    getTreeData() {
      var infoboxContainer = document.getElementById("bubble");
      window.$disaviewer.customInfobox = infoboxContainer;
      //点击对象查询对象属性
      var table = document.getElementById("tab");
      let that = this;
      window.$disaviewer.pickEvent.addEventListener((feature) => {
        if (that.tableTree) {
          for (let i = table.rows.length - 1; i > -1; i--) {
            table.deleteRow(i);
          }
          for (var key in feature) {
            if (key == "SMINDEXKEY") {
              // return;
            } else {
              var newRow = table.insertRow();
              var cell1 = newRow.insertCell();
              var cell2 = newRow.insertCell();
              cell1.innerHTML = key;
              cell2.innerHTML = feature[key];
            }
            console.log(key);
          }
          // if (that.tableTree) {
          //   $("#bubble").show();
          // } else {
          //   $("#bubble").remove();
          //   return;
          // }
        } else {
          return;
        }
      });

      $("#bubblePosition").click(function () {
        if ($("#bubblePosition").hasClass("fui-export")) {
          viewer.customInfobox = undefined;
          $("#bubble").removeClass("bubble").addClass("float");
          $("#bubblePosition").removeClass("fui-export").addClass("fui-bubble");
          $("#bubblePosition")[0].title = "悬浮";
          $("#bubble").css({ left: "82%", bottom: "45%" });
          $("#tableContainer").css({ height: "350px" });
        } else if ($("#bubblePosition").hasClass("fui-bubble")) {
          $("#bubble").removeClass("float").addClass("bubble");
          $("#bubblePosition").removeClass("fui-bubble").addClass("fui-export");
          $("#bubblePosition")[0].title = "停靠";
          $("#tableContainer").css({ height: "300px" });
          viewer.customInfobox = infoboxContainer;
        }
      });
      $("#close").click(function () {
        $("#bubble").hide();
      });

      //图层列表的隐藏显示
      $(document).on(
        "click.dropDown-container touchstart.dropDown-container",
        "[data-toggle=dropdown]",
        function (evt) {
          evt.stopPropagation();
          var target = evt.target;
          if (!target.contains(evt.currentTarget) && target.tagName != "SPAN") {
            return;
          }
          var $this = $(this),
            $parent,
            isActive;
          var $target = $this.children("div.dropDown-container");
          if ($target.length == 0) {
            $(".dropDown-container").removeClass("dropDown-visible");
            return;
          }
          isActive = $target.hasClass("dropDown-visible");
          $(".dropDown-container").removeClass("dropDown-visible");
          if (!isActive) {
            $target.addClass("dropDown-visible");
          }
          return false;
        }
      );
      // document.getElementById("position").addEventListener(
      //   "click",
      //   () => {
      //     this.getCameraView(viewer);
      //   },
      //   false
      // );
      var height = $("body").height() * 0.85 + "px";
      $("#treeContainer").css({
        height: height,
        "min-width": "260px",
        "text-align": "left",
      });
    },
    range(startID, endID) {
      var array = [];
      for (var i = startID; i < endID + 1; i++) {
        array.push(i);
      }
      return array;
    },
    modelSlicing() {
      let that = this;
      that.boxNew = true;
      let viewer = window.$disaviewer;
      let layers = window.$disalayers;
      console.log(window.$disalayers);
      that.setAllLayersClipColor(layers);
      var tooltip = createTooltip(document.body);
      var handlerBox = new Cesium.DrawHandler(viewer, Cesium.DrawMode.Box);
      var editorBox;
      var boxEntity = undefined;
      handlerBox.movingEvt.addEventListener((windowPosition) => {
        if (handlerBox.isDrawing) {
          tooltip.showAt(
            windowPosition,
            "<p>点击鼠标左键结束矩形绘制，移动鼠标绘制box高度。</p><p>右键结束绘制.</p>"
          );
        } else {
          tooltip.showAt(windowPosition, "<p>点击鼠标左键，开始绘制矩形作为box底面</p>");
        }
      });
      handlerBox.drawEvt.addEventListener(function (e) {
        boxEntity = e.object;
        var newDim = boxEntity.box.dimensions.getValue();
        var position = boxEntity.position.getValue(0);
        var boxOption = {
          dimensions: newDim,
          position: position,
          clipMode: "clip_behind_all_plane",
          heading: 0,
        };

        //box编辑
        editorBox = new Cesium.BoxEditor(viewer, boxEntity);
        editorBox.editEvt.addEventListener((e) => {
          boxEntity.box.dimensions = e.dimensions;
          boxEntity.position = e.position;
          boxEntity.orientation = e.orientation;
          setClipBox();
        });

        editorBox.distanceDisplayCondition = new Cesium.DistanceDisplayCondition(0, 950);
        editorBox.activate();
        that.setAllLayersClipOptions(boxOption);
        tooltip.setVisible(false);
        handlerBox.clear();
        handlerBox.deactivate();
      });
      handlerBox.activate();
      $("#clearbox").click(() => {
        for (var i = 0, j = layers.length; i < j; i++) {
          layers[i].clearCustomClipBox();
        }
        editorBox.deactivate();
        viewer.entities.removeAll();
        handlerBox.clear();
        handlerBox.activate();
        handlerBox.deactivate();
        console.log(handlerBox);
        console.log(editorBox);
      });

      function setClipBox() {
        if (typeof boxEntity == "undefined") {
          return;
        }
        var newDim = boxEntity.box.dimensions.getValue();
        var position = boxEntity.position.getValue(0);
        console.log(position);
        var heading = 0;
        if (typeof boxEntity.orientation != "undefined") {
          let rotationM3 = Cesium.Matrix3.fromQuaternion(
            boxEntity.orientation._value,
            new Cesium.Matrix3()
          );
          let localFrame = Cesium.Matrix4.fromRotationTranslation(
            rotationM3,
            Cesium.Cartesian3.ZERO,
            new Cesium.Matrix4()
          );
          let inverse = Cesium.Matrix4.inverse(
            Cesium.Transforms.eastNorthUpToFixedFrame(position),
            new Cesium.Matrix4()
          );
          let hprm = Cesium.Matrix4.multiply(inverse, localFrame, new Cesium.Matrix4());
          var rotation = Cesium.Matrix4.getMatrix3(hprm, new Cesium.Matrix3());
          let hpr = Cesium.HeadingPitchRoll.fromQuaternion(
            Cesium.Quaternion.fromRotationMatrix(rotation)
          );
          heading = hpr.heading;
        }

        var boxOptions = {
          dimensions: newDim,
          position: position,
          clipMode: "clip_behind_all_plane",
          heading: heading,
        };
        console.log(boxOptions);
        that.setAllLayersClipOptions(layers, boxOptions);
      }
    },
    box() {},
    setAllLayersClipColor(layers) {
      console.log(layers);
      for (var i = 0, j = layers.length; i < j; i++) {
        layers[i].clipLineColor = new Cesium.Color(1, 1, 1, 0);
      }
    },
    setAllLayersClipOptions(layers, boxOptions) {
      console.log("layers", layers);
      for (var i = 0, j = layers.length; i < j; i++) {
        layers[i].setCustomClipBox(boxOptions);
      }
    },
    getCameraView(viewer) {
      const camera = viewer.scene.camera;
      const cartographic = Cesium.Cartographic.fromCartesian(camera.position);
      const x = Cesium.Math.toDegrees(cartographic.longitude);
      const y = Cesium.Math.toDegrees(cartographic.latitude);
      const z = cartographic.height;
      let pt = Cesium.Cartographic.fromDegrees(x, y, z);
      let ellipsoid = viewer.scene.globe.ellipsoid;
      let cartesian3 = ellipsoid.cartographicToCartesian(pt);
      let objinfo = {
        经度: x,
        维度: y,
        高度: z,
        x: cartesian3.x,
        y: cartesian3.y,
        z: cartesian3.z,
        heading: camera.heading,
        pitch: camera.pitch,
        roll: camera.roll,
      };
      // this.CameraViewGo();
    },
    CameraViewGo(Num) {
      let obj, ori;
      // obj = Cesium.Cartesian3.fromDegrees(
      //   100.90148143056112,
      //   30.848622090088867,
      //   10.258280992165428
      // );
      obj = Cesium.Cartesian3.fromDegrees(100.55, 30.53, 10.258280992165428);
      ori = {
        heading: 0.18034747698162512,
        pitch: -0.38166153762145427,
        roll: 6.283185307179586,
      };
      switch (Num) {
        case 1:
          obj = Cesium.Cartesian3.fromDegrees(
            100.90215043678707,
            30.84862798929772,
            15.39286478533327
          );
          ori = {
            heading: 0.783785070287796,
            pitch: -0.3501326609910511,
            roll: 6.283185307179586,
          };
          break;
        case 2:
          obj = Cesium.Cartesian3.fromDegrees(
            100.90466580709172,
            30.84865911396735,
            30.75211630981211
          );
          ori = {
            heading: 5.880937663616124,
            pitch: -0.5460765258265332,
            roll: 6.283185307179586,
          };
          break;
        case 3:
          obj = Cesium.Cartesian3.fromDegrees(
            100.9058301966254,
            30.850174335980135,
            38.80240673381853
          );
          ori = {
            heading: 2.850744653029146,
            pitch: -0.6519305107623343,
            roll: 6.283185307179583,
          };
          break;
        case 4:
          obj = Cesium.Cartesian3.fromDegrees(
            100.90871069555234,
            30.85026572534762,
            44.392893682433105
          );
          ori = {
            heading: 5.7742925242458885,
            pitch: -0.6519340236203934,
            roll: 6.283185307179586,
          };
          break;
        case 5:
          obj = Cesium.Cartesian3.fromDegrees(
            100.91152512367756,

            30.851877836617653,
            23.27125239633514
          );
          ori = {
            heading: 4.511098726387877,
            pitch: -0.29113675025171215,
            roll: 6.283185307179576,
          };
          break;
      }
      window.$disaviewer.camera.flyTo({
        destination: obj, //经度、纬度、高度
        orientation: ori,
        duration: 3,
      });
    },
    getData() {
      var queryObj = {
        getFeatureMode: "ID",
        // "spatialQueryMode": "CONTAIN",
        datasetNames: ["NewDatasource:NewDataset"],
        ids: [id],
      };

      var queryData = JSON.stringify(queryObj);
    },
  },
};
</script>

<style lang="less" scoped>
#cesium {
  width: 100%;
  height: 100%;
  // background-color: white;
  position: relative;
  #position {
    position: absolute;
    top: 0px;
    right: 500px;
    z-index: 999999;
    color: white;
  }
  #bubble {
    z-index: 8;
    height: 400px;
    width: 300px;
    min-width: 400px;
    min-height: 350px;
    background-color: rgb(24, 46, 56);
    color: white;
  }
}
</style>
<style lang="less">
#tab {
  td {
    color: white;
  }
  th {
    color: white;
  }
  tr {
    background-color: transparent !important;
  }
}
#tab {
}
</style>
